import React from 'react'
// ===================================================================== common
import $addDelRows from '#private/common/add-del-rows'
// ===================================================================== Temp
import SubmitForm from '#cpt/temp/SubmitForm'
import Controls from '#cpt/temp/Controls'
import Confirm from '#cpt/temp/Confirm'
import Pinyin from '#cpt/temp/js/ChinesePY'
// ===================================================================== global declare
const { $fn, $Lazy, $http } = window
// ===================================================================== Lazy
const Page 		= $Lazy.load(()=>import('#tp/page/page-container-scroll'))
const Box 		= $Lazy.load(()=>import('#tp/box/box'))
const $cache 	= $Lazy.file(()=>import('#private/cache-api'))
//
const ProjectDetailTable 			= $Lazy.state(()=>import('../set-marketing-project/table/project-detail'))
const SuggestionsExplanationsTable 	= $Lazy.state(()=>import('../set-single-project/pages/d/table/suggestions-explanations'))
const TimeSet 						= $Lazy.state(()=>import('../cpt/time-set'))
const ProjectManual					= $Lazy.state(()=>import('../set-single-project/pages/f'))
// ===================================================================== component
class Index extends React.Component{
	state = {
		// 提交表单列表
		formData : [
			// 项目名称关联拼音简写 20220704 耿琰
			{ label: '项目中文名称',		name: 'kind_name', 			half:true, required:true, title:'项目信息', onChange:({value,formData})=>{
				this.formRef.setValue({'pinyin_name':Pinyin.getWordsCode(value)})
			}},
			{ label: '中文简称',			name: 'short_name', 		width:'25%', required:true },
			{ label: '拼音简写',		name: 'pinyin_name', 			width:'25%', },
			{ label: '项目英文名称',		name: 'name_en', 			half:true },
			{ label: '英文简称',			name: 'name_short_en', 		half:true },
			{ label: '组合项目代码',		name: 'kind_code', 			half:true, disabled:true },
			{ label: '项目助记码',		name: 'debit_code', 		half:true },
			{ label: '报告单模板',		name: 'report_id',			half:true, required:true,	type:'select', loading:true },
			{ label: '标本类型',			name: 'spec_type',			half:true, type:'select', loading:true, idStr:'code' },
			{ label: '上级质控',			name: 'superiorquality', 	half:true, suffix:'%'},
			{ label: '排序',			name: 'sort', 				half:true, type:'number'  },
			{ label: '是否配送打印',		name: 'printing', 			half:true, type:'checkbox'  },
			/* 2021-7-19  添加报告单外网不显示 --马婷 */
			{ label: '报告单外网不显示',		name: 'is_show_out', 	half:true, type:'checkbox',	value:0 },
			
			{ label: '汇总计算',			name: 'result_formula', 	half:true, br:true, bind:true, 
				onValue: option=>$fn.onEnabledBtn.call(this,'result_formula', option),
				btn:{ label:'添加', onClick: ()=>$addDelRows.addRows.call(this, this.state.formData, 'result_formula') }
			 },
			
			{ label: '岗位',			name: 'project_id',			half:true, required:true, type:'select', loading:true, br:true },
			{ label: '实验号模板',		name: 'low_board_id',		half:true, required:true, type:'select', loading:true },
			{ label: '项目标签模板',		name: 'tag_id',				half:true, required:true, type:'select', loading:true },
			
			{ label: '注意事项',			name: 'careful', 			half:true, type:'textarea', br:true  },
			{ label: '组合项目说明：(报告单注释内容)',name: 'remark', half:true, type:'textarea'  },
			{ label: '备注',			name: 'memo', 				full:true, type:'textarea',  },
		],
		offTips: {
			comb: [],
			market: [],
			single: [],
			sub: []
		}
	}
	
	componentDidMount(){
		const { kind_id } = $fn.query()
		this.submit = { kind_id }
		this.kind_id = kind_id
		this.setState({ kind_id })
		this.getSelect()
	}
	
	// 获取下拉数据
	getSelect = () => {
		const { formData } = this.state
		
		$cache.then( async f => {
			// 报告单模板
			$fn.setRow( formData, 'report_id',  await f.getCache({ api: 'report_template' }) )
			// 标本类型
			$fn.setRow( formData, 'spec_type',  await f.getDicCache({ code: 2000 }) )
			// 岗位
			$fn.setRow( formData, 'project_id',  await f.getCache({ api: 'gang_wei' }) )
			// 实验号模板
			$fn.setRow( formData, 'low_board_id',  await f.getCache({ api: 'num_template' }) )
			// 项目标签模板
			$fn.setRow( formData, 'tag_id',  await f.getCache({ api: 'tag_template' }) )
			//
			this.setState({ formData })
		})
	}
	
	fetch = () => {
		$http.submit(null,'kd-combin-project/info', { param:{uuid:this.kind_id}, isPull:true } ).then((data)=>{
			let { result_formula, report_time_set, kind_status } = data
			
			this.setState({ edit: +kind_status === 2 }, ()=>{
				const _d = $addDelRows.echoName.call(this,this.state.formData,'result_formula', result_formula)
				this.formRef.setValue({...data, result_formula:[], ..._d})
			})
			
			this.timeRef?.load?.(report_time_set)
			this.initSubmit = data
		})
		$http.submit(null, 'kind-info/offTips', { param:{kind_id:this.kind_id} }).then(data => this.setState({offTips: data}))
	}
	
	// 操作按钮
	controls = () => {
		const query = { uuid: this.kind_id }
		const { edit } = this.state
		if( edit === true){
			const { comb, market, single, sub } = this.state.offTips
			return [
				Confirm.call(this, '下架', 'kind-info/off', { param:this.kind_id, idStr:'kind_id', msg:
					<div>
					<span>{ single.length || sub.length || comb.length || market.length ? <span style={{color: 'red'}}>该项目下架，以下关联项目也将会被下架！</span> : '确认下架？' }</span><br />
						{ single.length ? <div>单一项目:【{single.join(',')}】<br /></div> : '' }
						{ sub.length ? <div>从属项目:【{sub.join(',')}】<br /></div> : '' }
						{ comb.length ? <div>组合项目:【{comb.join(',')}】<br /></div> : '' }
						{ market.length ? <div>营销项目:【{market.join(',')}】<br /></div> : '' }
					</div>,
					refresh:true, onComplete:()=>{
						this.setState({ edit: false })
				} }),
				Controls.back.call(this, { refresh:true })
			]
		}else if( edit === false){
			return [
				Confirm.call(this,'保存', null, { onMy: ()=> {
					this.setState({ isAudit: false })
					this.timeRef.onSubmit()
					this.submit.audit = ''
					setTimeout(()=>this.formRef.submit())
					$fn.dataRemove('specimen-kind/selectkind')
				}}),
				Confirm.call(this, '审批', 'kd-combin-project/audit', { query }),
				Confirm.call(this,'保存并提交审批', null, { onMy: ()=> { 
					this.setState({ isAudit: true })
					this.timeRef.onSubmit()
					this.submit.audit = 1
					setTimeout(()=>this.formRef.submit())
					$fn.dataRemove('specimen-kind/selectkind')
				}}),
				Confirm.call(this, '发布', 'kd-combin-project/push', { query }),
				Controls.back.call(this, { refresh:true })
			]
		}else{
			return []
		}
	}
	fd = {}
	render(){
		const tableStyle = {height:300, padding:'10px 0 10px'}
		const { kind_id } = this
		const { edit, isAudit } = this.state
		return (
			<Page title='设定标准组合项目' nobc controls={this.controls()}>
				<Box contentClassName='plr10' first>
					{ 
						SubmitForm.call(this,{ msg: isAudit ? '保存并提交审批':'保存', labelWidth:'s10', api:'kd-combin-project/edit', onLoad: this.fetch,
							disabled:edit,
							getSubmit: param =>{ 	// 处理提交数据
								const _fd = []
								for(let i in this.fd){
									if(!$fn.isValid(this.fd[i]['postpone'])){
										this.fd[i]['postpone'] = ''
									}
									_fd.push(this.fd[i])
								}
								const result_formula = $addDelRows.getSubmit(param, 'result_formula')
								const _f = $fn.hasArray(_fd) ? { report_time_set:_fd } : null
								return {..._f, ...result_formula}
							},
						}) 
					}
				</Box>
				{/* 发报告单时间设置 */}
				<TimeSet 
					onRef		= { ref=> this.timeRef=ref }
					disabled	= { edit }
					onSubmit 	= { value => {
						this.fd = { ...this.fd, ...value }
					}}
				/>
				{/* 项目明细 */}
				<ProjectDetailTable tableStyle={tableStyle} kind_id={kind_id} disabled={ edit } api='kd-combin-rel-kind/index' delApi='kd-combin-rel-kind/delete' addApi='kd-combin-rel-kind/addbybatch'/>
				{/* 建议与解释 */}
				<SuggestionsExplanationsTable tableStyle={tableStyle}  kind_id={kind_id} disabled={ edit }/>
				{/* 项目信息 */}
				<ProjectManual tableStyle={tableStyle}  kind_id={kind_id} />
			</Page>	
		)
	}
}

export default Index